package com.ghn.cocknovel.ui.activity.main

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Gravity
import android.view.KeyEvent
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.view.GravityCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.example.basemodel.base.BaseHeadVMActivity
import com.example.basemodel.base.DefaultHeadStyle
import com.example.basemodel.utils.NotificationUtils
import com.ghn.cocknovel.R
import com.ghn.cocknovel.databinding.ActivityMainBinding
import com.ghn.cocknovel.ext.GONE
import com.ghn.cocknovel.ext.VISIBLE
import com.ghn.cocknovel.net.task.LoginTask
import com.ghn.cocknovel.ui.activity.Information.InformationActivity
import com.ghn.cocknovel.ui.activity.main.vm.MainViewModel
import com.ghn.cocknovel.ui.activity.map.MapActivity
import com.ghn.cocknovel.ui.activity.map.vm.MapViewModel
import com.ghn.cocknovel.ui.activity.more.MoreActivity
import com.ghn.cocknovel.ui.activity.myorder.MyorderActivity
import com.ghn.cocknovel.ui.activity.setting.ChangePhoneNumberActivity
import com.ghn.cocknovel.ui.activity.setting.SettingActivity
import com.ghn.cocknovel.ui.activity.work.ToDayWorkTaskActivity
import com.ghn.cocknovel.ui.activity.work.WorkTasksActivity
import com.ghn.cocknovel.utils.PictureGlideEngine
import com.ghn.cocknovel.view.DialogClickListener
import com.ghn.cocknovel.view.DialogMessage
import com.google.android.material.navigation.NavigationView
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


class MainActivity : BaseHeadVMActivity<MainViewModel, ActivityMainBinding, DefaultHeadStyle>(),
    NavigationView.OnNavigationItemSelectedListener {
    lateinit var mUserDrawimage: ImageView
    val mMapViewModel by lazy { MapViewModel(application) }
    lateinit var mQueryTransitOrderDisposable: Disposable
    override fun layoutId(): Int = R.layout.activity_main

    @SuppressLint("WrongConstant", "SetTextI18n")
    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView(savedInstanceState: Bundle?) {
        mHeadStyle.setTitleColor("巡游DRT", getColor(R.color.white))
        mHeadStyle.setLeftImageResource(R.mipmap.home1)
        mHeadStyle.setTitleBackgroundColor(getColor(R.color.color_416ff8))
        mHeadStyle.mBinding.baseHeadBackBtn.setOnClickListener {
            if (mDatabind.drawerLayout.isOpen) {
                mDatabind.drawerLayout.closeDrawers()
            } else {
                mDatabind.drawerLayout.openDrawer(Gravity.START)
            }
        }
        mDatabind.drawerLayout.setOnClickListener {
            mDatabind.drawerLayout.closeDrawer(Gravity.START)
        }
        mDatabind.llRoot.setOnClickListener {
            mDatabind.drawerLayout.closeDrawers()
        }
        mDatabind.btnToDayWork.setOnClickListener {
            startActivity(Intent(this, ToDayWorkTaskActivity::class.java))
        }
        mDatabind.btnMyWork.setOnClickListener {
            startActivity(Intent(this, WorkTasksActivity::class.java))
        }
        mDatabind.btnMyOrder.setOnClickListener {
            startActivity(Intent(this, MyorderActivity::class.java))
        }
        mDatabind.btnSetting.setOnClickListener {
            startActivity(Intent(this, SettingActivity::class.java))
        }
        mDatabind.clLastTask.setOnClickListener {
            mViewModel.currentInformation.value?.also {
                if (it.taskState == 3) {
                    startActivity(
                        Intent(this, MapActivity::class.java)
                            .putExtra("taskId", it.taskId.toString())
                            .putExtra("fenceAreaId", it.fenceAreaId)

                    )
                }
            }
        }
        val slidingFrame = mDatabind.slidingFrame
        slidingFrame.setNavigationItemSelectedListener(this@MainActivity)
        val navheader = slidingFrame.inflateHeaderView(R.layout.nav_header)
        mUserDrawimage = navheader.findViewById<ImageView>(R.id.draw_imageview)
        val drawname = navheader.findViewById<TextView>(R.id.draw_tv_name)
        //抽屉布局中的司机信息
        mViewModel.getmessage()
//        mUserDrawimage.setOnClickListener {
//            startActivity(Intent(this, PictureActivity::class.java))
//        }
        mViewModel.message.observe(this) {
            drawname.setText(it?.driverName)
            Glide
                .with(this)
                .load(it?.driverAvatar)
                .apply(RequestOptions.bitmapTransform(CircleCrop()))
                .transition(DrawableTransitionOptions.withCrossFade(500))
                .into(mUserDrawimage)
        }
        navheader.setOnClickListener {
            PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .imageEngine(PictureGlideEngine.createGlideEngine())
                .forResult(100)
        }
        //更多
        mDatabind.btnMore.setOnClickListener {
            startActivity(Intent(this, MoreActivity::class.java))
        }

        mViewModel.onlinetime.observe(this) {
            mDatabind.tvtoDayHour.text = it?.todayDuration.toString() + "H"
        }
        //累计订单数统计
        mViewModel.getcumulative()
        mViewModel.cumulative.observe(this) {
            mDatabind.tvOrderNum.text = it?.finishOrderNum.toString()
            mDatabind.tvReturnOrderNum.text = it?.finishReturnOrderNum.toString()
        }

        mViewModel.lastInformation.observe(this) {
            mDatabind.tvLastTaskTest.text = it?.fenceAreaName
            mDatabind.tvCarNum.text = it?.carNumber
            mDatabind.tvCarPeopleNum.text = "载人数: " + it?.carCapacity
            mDatabind.tvLoginDeviceMeg.text = "登录设备信息: " + it?.loginDevice
            mDatabind.tvSumTime.text = "总时长: " + it?.duration
            mDatabind.tvSumDistance.text = "总里程" + it?.mileage + "千米"
            mDatabind.tvLoginDeviceMeg.visibility = if (it?.loginDevice == null) View.GONE else View.VISIBLE
            mDatabind.tvSumTime.visibility = if (it?.duration == 0.0) View.GONE else View.VISIBLE
            mDatabind.tvSumDistance.visibility = if (it?.mileage == 0.0) View.GONE else View.VISIBLE
            mDatabind.tvCarOverPeopleNum.GONE()
            mDatabind.tvCarPeopleNum2.GONE()
            mDatabind.tvCarPeopleNum.VISIBLE()
            mDatabind.tvSumTime.VISIBLE()
            mDatabind.tvSumDistance.VISIBLE()
        }

        mDatabind.tvTest.setOnClickListener {
//            NotificationUtils.showNotification(this, "导航提醒", "当前导航路径已经变化")
        }

        mQueryTransitOrderDisposable = Observable.interval(10, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                //任务详情页查询任务信息
                mMapViewModel.queryTransitOrder()
            }) {
            }
    }

    override fun createObserver() {
        mViewModel.upUserLogoUrlSuccess.observe(this) {
            mViewModel.driverUpdateTransitDriverInfo(it)
        }
        mViewModel.upUserLogoSuccess.observe(this) {
            dismissLoading()
            if (it) {
                showMsg("修改成功!")
                Glide
                    .with(this)
                    .load(mViewModel.upUserLogoUrlSuccess.value)
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .into(mUserDrawimage)
            }
        }
        mViewModel.currentInformation.observe(this) {
            it?.also {
                mDatabind.tvCarNum.text = it.carNumber
                mDatabind.tvLastTaskTest.text = it.fenceAreaName
                mDatabind.tvCarOverPeopleNum.GONE()
                mViewModel.queryTransitSeatStatistics(it.taskId.toString())
                mViewModel.queryDriverOrderStatisticsByTaskBean(it.taskId.toString())
            }
            mDatabind.tvLastTask.text = if (it != null && it.taskState == 3) "本次任务" else "上次任务"
        }
        mViewModel.queryTransitSeatStatisticsBeanLiveData.observe(this) {
            mDatabind.tvCarPeopleNum.GONE()
            mDatabind.tvSumTime.GONE()
            mDatabind.tvSumDistance.GONE()
            mDatabind.tvCarPeopleNum2.VISIBLE()
            mDatabind.tvLoginDeviceMeg.GONE()
            mDatabind.tvCarOverPeopleNum.VISIBLE()

            mDatabind.tvCarPeopleNum2.setTextColor(getColor(R.color.color_66666))
            mDatabind.tvCarOverPeopleNum.text = "余座：" + (mViewModel.currentInformation.value?.carCapacity!! - it.boardingAdultNum).toString()
        }
        mMapViewModel.queryPassengerBySite.observe(this) {
            //查询司机提示语【司机点弹窗触发后台关闭弹窗接口 后台设置关闭】【需要定时任务定时查询】
            //正常接单查询提示
            if (it?.canReceiveOrder == 1) {
                mMapViewModel.queryTransitPromptNet()
            }
        }
        mMapViewModel.mQueryTransitPromptBeanLiveData.observe(this) {
            NotificationUtils.showNotification(this, "", it.promptDesc)
            //关闭弹窗提示
            mMapViewModel.updateTransitPromptNet()
        }
        mViewModel.queryDriverOrderStatisticsByTaskBeanLiveData.observe(this) {
            mDatabind.tvCarPeopleNum2.text = "已售: " + it.totalOrderNum
        }

    }

    override fun onResume() {
        super.onResume()
        //获取任务信息
        mViewModel.getinformation()
        //首页中在线时常
        mViewModel.getonlinetime()
        if (!NotificationUtils.isOpenNotification(this)) {
            DialogMessage(this).setMessageTitle("通知打开获取更好的体验").setYesText("打开").setClickListener(object : DialogClickListener() {
                override fun yesClick(dailog: Dialog?) {
                    NotificationUtils.openSettingNotification(this@MainActivity)
                }
            }).show()
        } else if (!isLocationEnabled(this)) {
            DialogMessage(this).setMessageTitle("您的GPS需要打开才能更好的导航").setYesText("打开").setClickListener(object : DialogClickListener() {
                override fun yesClick(dailog: Dialog?) {
                    // 去打开 GPS
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    intent.addCategory(Intent.CATEGORY_DEFAULT)
                    startActivity(intent)
                }
            }).show()
        }
    }

    private fun isLocationEnabled(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }


    /**
     * 菜单的点击事件
     */
    @SuppressLint("CommitTransaction")
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.fragment_phone -> {
                mDatabind.drawerLayout.closeDrawer(GravityCompat.START)
                startActivity(Intent(this, ChangePhoneNumberActivity::class.java))
            }

            R.id.fragment_information -> {
                startActivity(Intent(this, InformationActivity::class.java))
                mDatabind.drawerLayout.closeDrawer(GravityCompat.START)
            }

            R.id.fragment_statistics -> {
                startActivity(Intent(this, MoreActivity::class.java))
                mDatabind.drawerLayout.closeDrawer(GravityCompat.START)
            }

            R.id.fragment_settings -> {
                mDatabind.drawerLayout.closeDrawer(GravityCompat.START)
                startActivity(Intent(this, SettingActivity::class.java))
            }
        }
        return false
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                100 -> {
                    val resultData = PictureSelector.obtainMultipleResult(data)
                    resultData[0].also {
                        showLoading()
                        mViewModel.uploadFileNet(it.realPath)
                    }
                }
            }
        }
    }


    //重写onKeyDown()方法,继承自退出的方法
    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                showMsg("再按一次退出")
                exitTime = System.currentTimeMillis()
            } else {
                finish()
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        LoginTask.stopTask()
        super.onDestroy()
        if (mQueryTransitOrderDisposable != null) {
            mQueryTransitOrderDisposable.dispose()
        }
    }
}
